local skynet = require "skynet"
local protocol = require "protocol"

local message_dispatcher = {}

function protocol._add_handler_core(protoId, handler)
	if message_dispatcher[protoId] == nil then
		message_dispatcher[protoId] = { handler }
	else
		message_dispatcher[protoId][handler] = handler
	end
	print("add handler for protoId:", protoId)
	print("add handler address", skynet.self())
end

function protocol._remove_handler_core( protoId, handler )
	if message_dispatcher[protoId] ~= nil then
		message_dispatcher[protoId][handler] = nil
	end
	print("remove handler for protoId:", protoId)
	print("remove handler address", skynet.self())
end

function protocol.on_packet(protoId, packet, agent_source)
	print ("protoId:", protoId, "packet:", packet)
	print ("self:", skynet.self())
	local handlers = message_dispatcher[protoId]
	if handlers ~= nil then
		for key,handler in pairs(handlers) do
			skynet.call(handler, "lua", "on_packet", protoId, packet, agent_source)
		end
	end
end

skynet.start(function ()
	skynet.dispatch("lua", function(session, source, cmd, ...)
		local f = protocol[cmd]
		assert(f)
		skynet.ret(skynet.pack(f(...)))
	end)
end)
